package j.nawks.wx.api.persistence.db;

import j.nawks.wx.api.message.entity.request.ReqMessage;
import j.nawks.wx.api.persistence.DataPeristence;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public abstract class AbstractMysqlAdapter implements DataPeristence {

	private static final String INSERT_LOG = "INSERT INTO kc_log(content) VALUES(?)";

	public abstract void _init() throws ClassNotFoundException ;

	public abstract Connection getConnection() throws ClassNotFoundException,
			SQLException;

	public AbstractMysqlAdapter() {
		try {
			this._init();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void log(String plainText, ReqMessage message) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		try {
			conn = getConnection();
			pstmt = conn.prepareStatement(INSERT_LOG);
			pstmt.setString(1, plainText);
			pstmt.execute();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			if (pstmt != null) {
				try {
					pstmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
